package ssh

import (
	"strconv"
	"strings"
)

type (
	DfResult []*dfFileSystem

	dfFileSystem struct {
		// FileSystem 文件系统名称或设备路径（如磁盘分区、虚拟文件系统、网络存储等）
		FileSystem string `json:"file_system" xml:"file_system"`
		// Blocks 文件系统的总容量
		Blocks float64 `json:"blocks" xml:"blocks"`
		// Used 已使用的空间大小
		Used float64 `json:"used" xml:"used"`
		// Available 剩余可用空间大小
		Available float64 `json:"available" xml:"available"`
		// Usage 已用空间占总容量的百分比
		Usage float64 `json:"usage" xml:"usage"`
		// MountedOn 文件系统的挂载点（即访问该存储的目录路径）
		MountedOn string `json:"mounted_on" xml:"mounted_on"`
	}
)

/*
Df 查询磁盘空间的使用清空

	Filesystem                         1K-blocks      Used  Available Use% Mounted on
	overlay                           1052666484 121863968  877256328  13% /
	tmpfs                                  65536         0      65536   0% /dev
	shm                                    65536         0      65536   0% /dev/shm
	/dev/mapper/ubuntu--vg-ubuntu--lv 1052666484 121863968  877256328  13% /usr/share/zoneinfo/Etc/UTC
	/dev/mapper/datadebug-docker      4226408360  12486608 3999157208   1% /root/automation/test_new_1/BasicCode
*/
func (own *Client) Df() (DfResult, error) {
	result := make(DfResult, 0)
	res, err := own.Execute("df")
	if err != nil {
		return result, err
	}

	var start bool
	var name string
	for _, line := range strings.Split(res, "\n") {
		if !start {
			if strings.HasPrefix(line, "Filesystem") {
				start = true
			}

			continue
		}

		items := strings.Fields(line)
		switch len(items) {
		case 1:
			name = items[0]
		case 5:
			fs := &dfFileSystem{}
			fs.FileSystem = name
			fs.Blocks, _ = strconv.ParseFloat(items[0], 64)
			fs.Used, _ = strconv.ParseFloat(items[1], 64)
			fs.Available, _ = strconv.ParseFloat(items[2], 64)
			fs.Usage, _ = strconv.ParseFloat(strings.Split(items[3], "%")[0], 64)
			fs.MountedOn = items[4]
			result = append(result, fs)
		case 6:
			fs := &dfFileSystem{}
			fs.FileSystem = items[0]
			fs.Blocks, _ = strconv.ParseFloat(items[1], 64)
			fs.Used, _ = strconv.ParseFloat(items[2], 64)
			fs.Available, _ = strconv.ParseFloat(items[3], 64)
			fs.Usage, _ = strconv.ParseFloat(strings.Split(items[4], "%")[0], 64)
			fs.MountedOn = items[5]
			result = append(result, fs)
		}
	}

	return result, nil
}
